package com.keai.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.keai.constant.MessageConst;
import com.keai.entity.PageResult;
import com.keai.entity.QueryPageBean;
import com.keai.entity.Result;
import com.keai.pojo.SysUser;
import com.keai.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/user")
public class UserController {

    @Reference
    UserService userService;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    //登录成功后,重定义到main.html
    @RequestMapping("/loginSuccess")
    public String loginSuccess(){
        return "redirect:http://localhost:83/pages/main.html";
    }

    //登录失败后，重定向到登录页面
    @RequestMapping("/loginFail")
    public String loginFail(){
        System.out.println("登录失败");
        return "redirect:http://localhost:83/login.html?param=loginFail";
    }



    @ResponseBody
    @RequestMapping("/findUsername")
    public Result findUsername(){
        try {
            //获取安全框架的上下文对象（全局对象）（包含了用户信息）
            SecurityContext securityContext = SecurityContextHolder.getContext();
//        获取认证对象
            Authentication authentication = securityContext.getAuthentication();
//        获取用户对象
            Object principal = authentication.getPrincipal();
            User user = (User) principal;
            //获取用户名
            String username = user.getUsername();
            return new Result(true, MessageConst.GET_USERNAME_SUCCESS, username);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.GET_USERNAME_FAIL);
        }

    }
    @RequestMapping("/findMenu")
    @ResponseBody
    public Result findMenu(String username){
        try {
            List<Map<String,Object>> menuList=userService.findMenu(username);
            for (Map<String, Object> map : menuList) {
                System.out.println(map);
            }
            return new Result(true,MessageConst.GET_MENU_SUCCESS,menuList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.GET_MENU_FAIL);
        }

    }
    @RequestMapping("/findPage")
    @ResponseBody
    @PreAuthorize("hasAuthority('USER_QUERY')")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        PageResult pageResult= userService.findPage(queryPageBean);
        return pageResult;
    }

    //添加方式一：使用map接收数据，并反序列化
    @RequestMapping("/add")
    @ResponseBody
    @PreAuthorize("hasAuthority('USER_ADD')")
    public Result add(@RequestBody Map<String,Object> map){
        JSONArray jsonArray = (JSONArray) map.get("roleIds");
        Integer[] roleIds=jsonArray.toArray(new Integer[]{});

        JSONObject jsonObject= (JSONObject) map.get("user");
        SysUser user = jsonObject.toJavaObject(SysUser.class);
        //密码加密
        String encode = bCryptPasswordEncoder.encode(user.getPassword());
        user.setPassword(encode);
        try {
            userService.add(roleIds,user);
            return new Result(true, MessageConst.ADD_USER_SUCCESS);
        } catch (RuntimeException e) {
            e.printStackTrace();
            return new Result(false, e.getMessage());
        }
        catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConst.ADD_USER_FALL);
        }
    }

    @RequestMapping("/findById")
    @ResponseBody
    @PreAuthorize("hasAuthority('USER_QUERY')")
    public Result findById(Integer id){
        try {
            SysUser user =userService.findById(id);
            return new Result(true, MessageConst.QUERY_USER_SUCCESS,user);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConst.QUERY_USER_FALL);
        }
    }

    @ResponseBody
    @RequestMapping("/findUserIdsByUserId")
    @PreAuthorize("hasAuthority('USER_QUERY')")
    public Result findUserIdsByUserId(Integer id){
        try {
            Integer [] roleIds =  userService.findUserIdsByUserId(id);
            return new Result(true,MessageConst.QUERY_USER_SUCCESS,roleIds);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.QUERY_USER_FALL);
        }
    }
    @RequestMapping("/edit")
    @ResponseBody
    @PreAuthorize("hasAuthority('USER_EDIT')")
    public Result edit(@RequestBody Map<String,Object> map){
        JSONArray jsonArray = (JSONArray) map.get("roleIds");
        Integer[] roleIds=jsonArray.toArray(new Integer[]{});

        JSONObject jsonObject= (JSONObject) map.get("user");
        SysUser user = jsonObject.toJavaObject(SysUser.class);
        //密码加密
        String encode = bCryptPasswordEncoder.encode(user.getPassword());
        user.setPassword(encode);
        try {
            userService.edit(roleIds,user);
            return new Result(true, MessageConst.UPDATE_USER_SUCCESS);
        } catch (RuntimeException e) {
            e.printStackTrace();
            return new Result(false, e.getMessage());
        }
        catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConst.UPDATE_USER_FALL);
        }
    }

    @RequestMapping("/delById")
    @ResponseBody
    @PreAuthorize("hasAuthority('USER_DELETE')")
    public Result delById(Integer id){
        try {
            userService.delById(id);
            return new Result(true, MessageConst.DELETE_USER_SUCCESS);
        } catch (RuntimeException e) {
            e.printStackTrace();
            return new Result(false, e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConst.DELETE_USER_FALL);
        }
    }
}
